import ImportData from "@/components/ImportData";
import { s_getRole, s_getRoleUserList, s_getUnAllocateUsers, s_saveRole, s_updateRoleAllocate } from "@/services/basis";
import { ActionType, heILIntl, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormText, ProTable } from "@ant-design/pro-components";
import { Button, Card, Col, Flex, Input, message, Modal, Row, Space, Table, TableColumnProps, Tag } from "antd";
import moment from "moment";
import { useRef, useState } from "react";

const App:React.FC=()=>{
    const [selectedRows,setSelectedRows]=useState<DataType[]>([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [etype,setEtype]=useState(0);//0编辑，1新增
    const [openRole,setOpenRole]=useState(false);
    const [openRole2User,setOpenRole2User]=useState(false);

    const [selectedUsers,setSelectedUsers]=useState<React.Key[]>([]);
    const [allocateType,setAllocateType]=useState(1); //1新分配用户，0取消分配
    const [openAllocate,setOpenAllocate]=useState(false);

    const form_role=useRef<ProFormInstance>();
    const table_role=useRef<ActionType>();
    const table_allocate=useRef<ActionType>();
    const table_doallocate=useRef<ActionType>();

    const [selectedRowKeys3,setSelectedRowKeys3]=useState<React.Key[]>([]);

        
    interface DataType{
        x_id:number,
        id:number,
        code:string,
        name:string,
        status:number,
        operate_time:string,
        operater_id:string,
    }

    const columns:ProColumns<DataType>[]=[
        {
         key:'id',
         dataIndex:'id',
         title:'ID',
         hidden:true,
        },
        {
            key:'code',
            dataIndex:'code',
            title:'编码',
        },
        {
           dataIndex:'name',
           title:'角色名称',
           ellipsis:true,
          },
        {
            dataIndex:'status',
            title:'状态',
            render:(text)=>{
                switch (text) {
                    case 1: return <>正常</>;break;
                    case 2: return <Tag color="blue">冻结</Tag>;break;
                    case 3 :return <Tag color='red'>删除</Tag>;break;
                }
            },
        }
    ];
    //已分配用户表
    interface DataType2{
        id:number,
        role_id:number,
        user_id:number,
        code:string,
        name:string,
        org_name:string,
        role_name:string,
        status:number,
    }
    const columns2:ProColumns<DataType2>[]=[
        {key:'id',title:'ID',dataIndex:'id',hidden:true},
        // {dataIndex:'user_id',title:'用户ID'},
        {title:'角色',dataIndex:'role_name'},
        {title:'用户编码',dataIndex:'code'},
        {title:'用户姓名',dataIndex:'name'},
        {title:'部门',dataIndex:'org_name'},
        {title:'状态',dataIndex:'status',
            render:(text)=>text==1?<>正常</>:text==2?<Tag color="blue">冻结</Tag>:<Tag style={{color:'red'}}>失效</Tag>},
    ];

    //未分配用户表
    interface DataType3{
        id:number,
        org_name:string,
        code:string,
        name:string,
        sex:number,
    }
    const columns3:ProColumns<DataType3>[]=[
       {dataIndex:'id',title:'用户ID',key:'id'},
       {dataIndex:'org_name',title:'部门',},
       {dataIndex:'code',title:'用户编码'},
       {dataIndex:'name',title:'姓名'},
       {dataIndex:'sex',title:'性别',render:(text)=>text==1?<>男</>:<>女</>},
    ];

    async function addRole(){
       setEtype(1);
       form_role.current?.resetFields();
       table_role.current?.reset?.();
       setSelectedRows([]);
       setSelectedRowKeys([]);
 
       setOpenRole(true);
    }

    async function editRole(){
        if(selectedRows.length==0)
            message.warning('请先选择要编辑的角色。')
        else{
           setEtype(0);
           setOpenRole(true)
          // alert(JSON.stringify(selectedRows));
        };
    }

    async function saveRole(){
       const fdata=form_role.current?.getFieldsValue();
       const fdata2={...fdata,
                      operate_time:moment().format('YYYY-MM-DD HH:mm:ss'),
                     };
       const x=await s_saveRole({x_id:1,operater_id:1,etype,fdata:fdata2});//x_id,operater_id,etype,fdata
       if(x.success){
           message.success('数据保存成功！');
           setSelectedRows([]);
           table_role.current?.reloadAndRest?.();
          }
        else
           message.error('数据保存失败！');
       setOpenRole(false);
    }

    async function allocateRole(){
        if(selectedRowKeys.length==0)
            message.warning('请先选择要分配的角色。')
        else{
           setSelectedUsers([]);
           setAllocateType(1);//etype:1新分配，2取消分配,3重新分配
           setOpenAllocate(true);
        };
    }

    async function removeAllocateRole(){
        if(selectedUsers.length==0)
            message.warning('请先选择要取消分配的用户。')
        else{
           setAllocateType(2);
           //注意：user_ids是一个数组，在数据库端需要拆分处理。etype:1新分配，2取消分配,3重新分配
           const x=await s_updateRoleAllocate({x_id:1,operater_id:1,etype:2,role_id:selectedRowKeys[0],user_ids:selectedUsers});
           if(x.success){
              message.success('成功取消分配的用户。');
              table_allocate.current?.reloadAndRest?.();
              setSelectedUsers([]);
             }
            else
              message.error('执行错误，请联系管理员。');
        };
    }
   
    async function resetAllocateRole(){
        if(selectedUsers.length==0)
            message.warning('请先选择要恢复分配的用户。')
        else{
           setAllocateType(3);
           //注意：user_ids是一个数组，在数据库端需要拆分处理。etype:1新分配，2取消分配,3重新分配
           const x=await s_updateRoleAllocate({x_id:1,operater_id:1,etype:3,role_id:selectedRowKeys[0],user_ids:selectedUsers});
           if(x.success){
               message.success('成功恢复分配的用户。');
               table_allocate.current?.reloadAndRest?.();
               setSelectedUsers([]);
              }
           else
              message.error('执行错误，请联系管理员。');
        };
    }

    //保存新分配用户信息
    async function updateRole2user(){
        if(selectedRowKeys3.length==0)
            message.warning('请选择要分配的用户。');
        else{
            const x=await s_updateRoleAllocate({x_id:1,operater_id:1,etype:1,role_id:selectedRowKeys[0],user_ids:selectedRowKeys3});
           if(x.success){
               message.success('成功分配新用户。');
               table_allocate.current?.reloadAndRest?.();
               setSelectedUsers([]);
               setSelectedRowKeys3([]);
               table_doallocate.current?.reset?.();

               setOpenRole2User(false);
              }
           else
              message.error('执行错误，请联系管理员。');
        };
        } 
    //关闭用户分配窗口
    function closeRole2User(){
        setOpenAllocate(false);
        table_doallocate.current?.reset?.();
    }
    
    return(
        <>
        <Row gutter={8}>
            <Col span={8}>
            <ProCard style={{height:700,overflow:'auto'}} title='角色列表'   
               extra={<Space>
                <Button onClick={()=>addRole()}>新增</Button>
                <Button onClick={()=>editRole()}>编辑</Button>
                <ImportData  x_id={1} source='importdata' tdata={{data:'base_role'}} operater_id={1}  />
               </Space>}
            >
                {/* {JSON.stringify(selectedRows)} */}
                <ProTable<DataType>
                  actionRef={table_role}  
                  rowKey='id'
                  columns={columns}    
                  rowSelection={{
                      type:'radio',
                       onChange:(selectedKeys,selectedRows)=>
                        {
                            setSelectedRows(selectedRows);
                            setSelectedRowKeys(selectedKeys);
                            table_allocate.current?.reloadAndRest?.();
                            //alert(JSON.stringify(selectedRowKeys))
                        },
                    //  selectedRowKeys,
                    //  onSelect:(selectedKeys,selected,selectedRows)=>
                    //     {
                    //         setSelectedRows(selectedRows);
                     
                    //     }
                     
                  }} 
                  
                //   onRow={(record,index)=>{   //能够单周选中行，但无法更新选择的数据
                //     return {
                //         onClick:()=>{
                //             setSelectedRowKeys([record.id]);
                //             setSelectedRows([record]);
                //             table_allocate.current?.reloadAndRest?.();
                //            // alert(selectedRowKeys);
                //         },
                //     }
                //   }}
                 
                 request={async (params)=>{
                    //alert(JSON.stringify(params));
                    const x=await s_getRole({x_id:1,id:0});
                    return {
                        data:x.data,
                        success:true,
                    }
                }}
                search={false}
                scroll={{y:430}}
                pagination={{
                    pageSize:9,
                }}
                
                />
            </ProCard>
            </Col> 
            
            <Col span={16}>
            <ProCard style={{height:700,overflow:'auto'}} title='分配用户列表'
               extra={<Space size='large'>
                    <Button onClick={()=>allocateRole()}>分新配用户</Button>
                    <Button onClick={()=>removeAllocateRole()}>取消分配用户</Button>
                    <Button onClick={()=>resetAllocateRole()}>恢复分配用户</Button>

                </Space>}>
                <ProTable<DataType2> 
                   actionRef={table_allocate}
                   search={false}
                   columns={columns2}
                   rowKey='id'
                   request={async (params)=>{
                     const role_id=selectedRowKeys.length==0?0:Number.parseInt(selectedRowKeys[0].toString());
                     const x=await s_getRoleUserList({role_id});
                     return {
                        data:x.data,
                        success:true,
                      }
                   }}
                   scroll={{y:430}}
                   rowSelection={{
                    type:'checkbox',
                    onChange:(selectedRowKeys,selectedRows)=>setSelectedUsers(selectedRowKeys),
                   }}
                   pagination={{
                    pageSize:9,
                   }}
                />
            </ProCard>
            </Col>  
           
           {/* 角色编辑对话框 */}
           <Modal title={etype==0?'编辑角色':'新增角色'} onCancel={()=>setOpenRole(false)} open={openRole}
             closable destroyOnClose onOk={async ()=>await saveRole()} width={900}
            >
              <ProCard style={{height:'50vh',overflow:'auto'}}>
              <ProForm formRef={form_role} style={{width:300,marginLeft:68}} submitter={false} 
                   initialValues={
                    selectedRows.length==0?
                           {status:1,operate_time:moment(moment().toDate()).format('YYYY-MM-DD'),operater_id:1}
                        :{id:selectedRows[0].id,code:selectedRows[0].code,name:selectedRows[0].name,
                            status:selectedRows[0].status,operater_id:selectedRows[0].operater_id,
                            operate_time:moment(moment(selectedRows[0].operate_time).toDate()).format('YYYY-MM-DD'),
                        }
                }
              >
                <ProFormText name='id' hidden/>
                
                <ProFormText name='code' label='角色编码'
                   rules={[{required:true,message:'必须录入编码。'}]} />
                <ProFormText name='name' label='角色名称'
                   rules={[{required:true,message:'必须录入名称。'}]} />
                <ProFormRadio.Group name='status' label='状态'
                   rules={[{required:true,message:'必须录入状态。'}]} 
                   options={[{label:'正常',value:1},
                            {label:'冻结',value:2,style:{color:'blue'}},
                            {label:'删除',value:3,style:{color:'red'}}]}
                   />
                <ProFormDatePicker name='operate_time' label='时间' />
                <ProFormText name='operater_id' label='操作人'/>

              </ProForm>
              </ProCard>
           </Modal>
           {/* 新增分配用户 */}
           <Modal title='分配新用户' open={openAllocate} onCancel={()=>closeRole2User()}  width={800}
                  destroyOnClose={true}  onClose={()=>closeRole2User()} onOk={()=>updateRole2user()}
                  closable={true}
            >
                <ProCard style={{height:'50vh',overflow:'auto'}}>
               <ProTable<DataType3>
                   actionRef={table_doallocate}
                   columns={columns3}
                   rowKey='id'
                   search={false}
                   rowSelection={{
                      type:'checkbox',
                      selectedRowKeys:selectedRowKeys3,
                      onChange:(selectedRowKeys,selectedRows)=>setSelectedRowKeys3(selectedRowKeys),
                   }}
                   request={async (params)=>{
                      const x=await s_getUnAllocateUsers({role_id:Number.parseInt(selectedRowKeys[0].toString())});
                      return {
                        data:x.data,
                        success:true,
                      }
                   }}
                   scroll={{y:'40vh'}}
                  />
             </ProCard>
           </Modal>
        </Row>
    
     </>
);
}

export default App;